import React, { Component } from 'react'
import { backUrl } from 'lib/fun'
import Ajax from 'lib/Ajax'

export default class Edit extends Component {
	constructor(props) {
    super(props);
    this.contentKey = 'content';
    this.um = false;
    this.state = {
      msgData: {},
      loading: false
    }
    this.other = {};
  }



	componentDidMount(){
		this.childDidMount();
		// this.initUeditor();
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
      this.um&&(this.um.setContent(""));
      this.reset();
    }else{
      if(!this.um){
        this.initUeditor();
      }
      this.initOther();
      if(nextProps.type == 'edit'&&!this.props.visible){
        this.fetchMsg(nextProps.editId);
      }
    }
  }

  componentWillUnmount() {
    this.um&&this.um.destroy();
    this.unmountOther();
  }

  checkData = () => {
    return true
  }
  initOther = () => {}
  msgCallback = () => {}
	reset = () => {}
  childDidMount = () => {}
  unmountOther = () => {}

  handleCommit = ()=>{
    const self = this;
    self.props.form.validateFields((err, values) => {
      if(err == null&&!this.state.loading){
        self.setState({
          loading: true
        });
        const { type  } = self.props;
        if(self.props.type == 'edit'){
          values[self.itemKey] = this.props.editId;
        }
        this.um&&(values[self.contentKey] = self.um.getContent());
        const checkout = this.checkData(values);
        if(!checkout){
          message.info('数据校验错误！');
          return
        }
        Ajax({
          url: self.api.save,
          data: Object.assign(values, this.other),
          success: function(data){
            self.setState({
              loading: false
            });
            self.props.onOk(self.props.type);
          },
          error: function(error){
            self.setState({
              loading: false
            });
            message.error(error);
          }
        });
      }
    });
  }

  onCancel = ()=>{
    this.props.onCancel()
  }

  initUeditor = (ueditor = 'ueditor', objKey = 'um', contentKey = 'contentKey')=>{
    var self = this;
    window.UMEDITOR_CONFIG.toolbar = [
            'source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat |',
            'insertorderedlist insertunorderedlist | selectall cleardoc paragraph | fontfamily fontsize' ,
            '| justifyleft justifycenter justifyright justifyjustify |',
            'link unlink | emotion image video',
            '| horizontal preview fullscreen', 'drafts',
        ];
    if(document.getElementById(ueditor)){
      self[objKey] = window.UM.getEditor(ueditor, {
        imageUrl: backUrl('/admin/uploadfile'),
        imagePath:"/",
        lang:/^zh/.test(window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage) ? 'zh-cn' : 'en',
        langPath:window.UMEDITOR_CONFIG.UMEDITOR_HOME_URL + "lang/",
        autoHeight: true,
      });
			self[objKey].ready(function() {
        // console.log('loaded');
				//设置编辑器的内容
				if(self.state.msgData[self[contentKey]]){
					self[objKey].setContent(self.state.msgData[self[contentKey]]);
				}
			});
    }else{
      setTimeout(function(){
        self.initUeditor(ueditor, objKey, contentKey);
      }, 1000);
    }
  }

  fetchMsg = (id) => {
    var self = this;
    const { editId, type } = this.props;
    self.setState({
      loading: true
    });
    Ajax({
      url: this.api.get,
      data: {
        [self.itemKey]: id
      },
      success: function(result){
        self.setState({
          msgData: result,
          loading: false
        });
        self.msgCallback(result);
      },
      error: function(error){
        message.info(error||'请求失败');
      }
    });
  }

}
